package com.example.result.books

import android.content.Context
import android.os.Environment
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Book
import androidx.compose.material3.Icon
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.times
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import java.io.File

@Composable
fun BooksScreen(
    books: List<Book>,
    directoryChange: DirectoryChange,
    modifier: Modifier = Modifier,
    navigate: (String) -> Unit,
) {
    val listState = rememberLazyListState()
    LaunchedEffect(books) {
        listState.scrollToItem(0)
    }
    LazyColumn(
        modifier = modifier
            .padding(16.dp),
        state = listState
    ) {
        items(books, key = { it.path() }) {

            BookContent(it, directoryChange) { path ->
                if (it.isDir) {
                    directoryChange.moveDown(it)
                } else {
                    navigate(path)
                }
            }
        }
    }
}


@Composable
private fun BookContent(
    book: Book,
    directoryChange: DirectoryChange,
    goWebView: (String) -> Unit
) {
    val modifier = Modifier.padding(start = 1 * 8.dp)
    if (!book.isDir) {
        SuggestionChip(modifier = modifier, onClick = {
            goWebView(book.path())
        }, label = { Text(text = book.name) }, icon = {
            Icon(Icons.Filled.Book, contentDescription = "")
        })
    } else {
        SuggestionChip(modifier = modifier,
            onClick = { directoryChange.moveDown(book) },
            label = { Text(text = book.name) },
            icon = {
                Icon(
                    Icons.Filled.Add,
                    contentDescription = "",
                    modifier = Modifier
                        .padding(end = 8.dp)
                )
            })
    }
}

interface DirectoryChange {
    fun moveDown(book: Book)
    fun moveUp()
    fun refresh()
    fun switchTo(path: String)
    val currentDir: StateFlow<Book?>
    val recentExplorer: Flow<List<String>>
}

interface BookSort {
    val currentBookSort: StateFlow<BookSortType>
    fun sort(bookSortType: BookSortType)
}

enum class SortType(val displayName: String) {
    Asc("升序"),
    Desc("降序")
}

enum class SortCategory(val displayName: String) {
    Name("名称"),
    TotalSpace("大小"),
    ModifierTime("时间")
}

data class BookSortType(val sortType: SortType, val sortCategory: SortCategory)

interface DirectoryManager : DirectoryChange, BookSort {
    fun addBookMark(bookMark: String)
    fun removeBookMark(bookMark: String)
    fun createFile(name: String)
}

interface FileOperation {
    fun saveToFile(content: String, name: String)
    fun shareFile(context: Context, path: String)
    fun uploadFile(path: String)
}

const val ASSET_PREFIX = "file:///android_asset/"

const val FILE_PREFIX = "file:///"

fun doSaveToFile(context: Context, name: String, content: String): File {
    val dir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
    val path = File(dir, name)
    path.outputStream().bufferedWriter().use { file ->
        file.write(content)
    }
    return path
}
